package com.jp.juc.tools;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.ReentrantLock;

public class UseCountDownLatch2 {


    // 等待所有人准备好，开始抢微波炉热饭

    static CountDownLatch startFlag = new CountDownLatch(6);

    // 非公平锁
    static ReentrantLock reentrantLock = new ReentrantLock(false);

    static ExecutorService executorService = Executors.newFixedThreadPool(10);

    public static void main(String[] args) {

        List<Person> list = new ArrayList<>();

        list.add(new Person("小白"));
        list.add(new Person("小航"));
        list.add(new Person("小黑"));
        list.add(new Person("小李"));
        list.add(new Person("小罗"));
        for (Person person : list) {
            executorService.execute(person);
            startFlag.countDown();
        }
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        startFlag.countDown();
        executorService.shutdown();
    }


    private static class Person implements Runnable {
        public Person(String name) {
            this.name = name;
        }

        private final String name;

        @Override
        public void run() {
            try {
                System.out.printf("%s 我已经准备就绪%n", name);
                startFlag.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            reentrantLock.lock();
            System.out.printf("我是%s,我正在热饭%n", name);
            reentrantLock.unlock();

        }
    }
}
